<template>
    <div class="w-full flex justify-end items-center gap-2.5 box-border py-2.5">
        <n-date-picker
            type="month"
            v-model:value="timestamp"
            @update:value="handleChangeMonth"
        ></n-date-picker>
        <div
            ref="dateSelector"
            style="scroll-behavior: smooth"
            class="w-125 overflow-auto whitespace-nowrap ease"
            @wheel.prevent="handleWheel"
            @mousedown="startDrag"
            @mousemove.prevent="drag"
        >
            <div
                v-for="(item, index) in array"
                :key="index"
                @click="handleClickItem(item)"
                :class="{
                    focusable: activeIndex === item,
                }"
                class="inline-block font-size-4 w-20 mx-2.5 py-1 text-center bg-white cursor-pointer rounded-2xl"
            >
                {{ item }}
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, onActivated } from "vue";

const props = defineProps<{
    timestamp: number;
}>();
const emits = defineEmits(["update:timestamp"]);

const dateSelector = ref<HTMLElement | null>(null);

const timestamp = ref(props.timestamp);

const activeIndex = ref(new Date(props.timestamp).getDate());
const array = Array.from({ length: 31 }, (_, i) => i + 1);

onActivated(() => {
    if (dateSelector.value) {
        dateSelector.value.scrollLeft += (activeIndex.value - 1) * 100;
    }
});

const getTargetTimestep = (): number => {
    const date = new Date(timestamp.value);
    const year = date.getFullYear();
    const month = date.getMonth();
    const targetTimestamp = Date.UTC(year, month, activeIndex.value);
    return targetTimestamp;
};

// 滚轮滚动滑动条会改变
const handleWheel = (e: WheelEvent) => {
    const target = e.currentTarget as HTMLElement;
    target.scrollLeft += e.deltaY;
};
const startX = ref(0);
const scrollLeft = ref(0);

// 拖拽开始动作
const startDrag = (e: MouseEvent) => {
    startX.value = e.pageX;
    const target = e.currentTarget as HTMLElement;
    scrollLeft.value = target.scrollLeft;
};

// 拖拽效果
const drag = (e: MouseEvent) => {
    if (e.buttons !== 1) {
        return;
    }
    const x = e.pageX;
    const walk = (x - startX.value) * 2; // 敏感度
    const target = e.currentTarget as HTMLElement;
    target.scrollLeft = scrollLeft.value - walk;
};

const handleClickItem = (index: number) => {
    activeIndex.value = index;
    emits("update:timestamp", getTargetTimestep());
};

const handleChangeMonth = (value: number) => {
    timestamp.value = value;
    emits("update:timestamp", getTargetTimestep());
};
</script>

<style scoped>
.focusable {
    background-color: #e6e6e6;
}
</style>
